package com.wpf.servlet;

import com.wpf.bean.Userbean;
import com.wpf.dao.UserDAO;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Pattern;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class AddData extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public AddData() {}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
		UserDAO userdao = new UserDAO();
		Userbean userbean = new Userbean();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Pattern pattern = Pattern.compile("^[1-9]\\d*|0$");
		String ID = request.getParameter("id");
		String UserName = request.getParameter("username");
		String PassWord = request.getParameter("password");
		String ComPass = request.getParameter("compass");
		String Email = request.getParameter("email");
		String Birthday = request.getParameter("birthday");
		if(ID==""||ID==null) {
			request.setAttribute("Message", "<font size='1' color='red'>学号不能为空！</font>");
		}else if(!pattern.matcher(ID).matches()) {
			request.setAttribute("Message", "<font size='1' color='red'>学号格式不正确！</font>");
		}else if(!PassWord.equals(ComPass)){
			request.setAttribute("Message", "<font size='1' color='red'>两次密码不一致！</font>");
		}else {
			userbean.setId(Integer.parseInt(ID));
			userbean.setUsername(UserName);
			userbean.setPassword(PassWord);
			userbean.setEmail(Email);
			try {userbean.setBirthday(sdf.parse(Birthday));} catch (ParseException e) {};
			if(userdao.insert(userbean)) {
				request.setAttribute("Message", "<font size='1' color='orange'>添加成功！</font>");
			}else {
				request.setAttribute("Message", "<font size='1' color='red'>学号已存在或数据库未开启！添加失败！</font>");
			}
		}
		request.getRequestDispatcher("/wpf_insert.jsp").forward(request, response);
	}
}
